package com.example.fmgidsprototype;


import java.io.InputStream;
import java.util.Date;
import java.util.List;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.MediaController.MediaPlayerControl;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.widget.ViewSwitcher;

import com.example.fmgidsprototype.data.DataManager;
import com.example.fmgidsprototype.model.Category;
import com.example.fmgidsprototype.model.Review;
import com.example.fmgidsprototype.model.Venue;
import com.example.fmgidsprototype.webservice.n_cst_common;
import com.google.android.gms.maps.model.LatLng;



public class VenueDetailFragment extends Fragment implements MediaPlayerControl{
	
	private int mCurrentPage;
	private ImageView bigImg;
	private TextView venueAddress;
	private TextView venueName;
	private TextView addReviewIcon;
	private TextView venueDescription;
	private ImageView footerImg;
	private RatingBar ratingBar;
	private InputStream stream;
	private Context ctx;
	private RelativeLayout reviewBtn;
	private ToggleButton toggleView;
	private DataManager dm;
	private ReviewAdapter rAdapter;
	private List<Review> reviews;
	private ViewSwitcher detailSwitcher;
	private TextView phoneText;
	private TextView urlText;
	private TextView audioIcon;
	private RelativeLayout audioBtn;
	private Venue currentVenue;
	private MediaPlayer player;
	private MediaController controller;
	private Handler handler = new Handler();
	
	public VenueDetailFragment(Context ctx){
		this.ctx = ctx;
	}
	 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        currentVenue = null;
        /** Getting the arguments to the Bundle object */
        Bundle data = getArguments();
        currentVenue = (Venue) data.getSerializable(AppConstants.SELECTED_VENUE);
        
        /** Getting integer data of the key current_page from the bundle */
        //mCurrentPage = data.getInt("current_page", 0);
 
    }
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    	
    	if(controller != null){
        	controller.hide();
        	controller = null;
        }
        if(player != null){
        	player.release();
        	player = null;
        }
    	
        final View v = inflater.inflate(R.layout.venue_detail, container,false);
        bigImg = (ImageView) v.findViewById(R.id.detail_bigImg);
        footerImg = (ImageView) v.findViewById(R.id.detail_footerImg);
		venueName = (TextView) v.findViewById(R.id.detail_venueName);
		
		venueAddress = (TextView) v.findViewById(R.id.detail_venueAddress);
		venueDescription = (TextView) v.findViewById(R.id.detail_venueDescription);
		toggleView = (ToggleButton) v.findViewById(R.id.detail_toggleViewBtn);
		ratingBar = (RatingBar) v.findViewById(R.id.detail_ratingBar);
		LinearLayout bigImgWrapper = (LinearLayout) v.findViewById(R.id.big_image_wrapper);
		reviewBtn = (RelativeLayout) v.findViewById(R.id.detail_addReview);
		addReviewIcon = (TextView) v.findViewById(R.id.detail_addReview_icon);
		audioIcon = (TextView) v.findViewById(R.id.detail_audio_btn_icon);
		audioBtn = (RelativeLayout) v.findViewById(R.id.detail_audioPlayer);

		audioBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(final View view) {
				
				try{
					String url = AppConstants.MEDIA_PATH + currentVenue.getAudioPath();
					Log.d("AUDIOBTN", url);
					if(player == null){
						player = new MediaPlayer();
						controller = new MediaController(getActivity());
						player.setAudioStreamType(AudioManager.STREAM_MUSIC);
						player.setDataSource(url);
						player.setOnErrorListener(new OnErrorListener() {	
							@Override
							public boolean onError(MediaPlayer mp, int what, int extra) {
								Log.e("ONERROR", String.format("Error(%s%s)", what, extra));
								return false;
							}
						});
						player.setOnPreparedListener(new OnPreparedListener() {
							@Override
							public void onPrepared(MediaPlayer mp) {
								Log.d("DURATION", "" + mp.getDuration());
								controller.setMediaPlayer(VenueDetailFragment.this);
								controller.setAnchorView(audioBtn);
								audioBtn.setOnTouchListener(new OnTouchListener(){
									@Override
									public boolean onTouch(View arg0,
											MotionEvent arg1) {
										controller.show();
										return false;
									}				
								});
								handler.post(new Runnable() {	
									@Override
									public void run() {
										controller.setEnabled(true);
										controller.show(0);
									}
								});
							}
						});
						player.setOnCompletionListener(new OnCompletionListener() {
							@Override
							public void onCompletion(MediaPlayer mp) {
								player.release();
								player = null;
							}
						});
						player.prepareAsync();
						
					}
				}
				catch(Exception ioe){
					ioe.printStackTrace();
				}
			}
			public void onPrepared(MediaPlayer player){
				player.start();
			}
		});
		detailSwitcher = (ViewSwitcher) v.findViewById(R.id.detail_viewSwitcher);
		ImageView iconView = (ImageView) v.findViewById(R.id.detail_cat_icon_thumb);
		Category category = currentVenue.getCategories().get(0);
		String colorString = Util.COLOR_CODES.get(category.getName().toLowerCase());
		
		if(colorString != null){
			int c = Color.parseColor(colorString);
			bigImgWrapper.setBackgroundColor(c);
			toggleView.setBackgroundColor(c);
		}
		
		if(category != null){
			String iconString = Util.CAT_ICONS.get(category.getName().toLowerCase());
			if(iconString != null){
				iconView.setImageResource(ctx.getResources().getIdentifier(Util.stripExtension(iconString), "drawable", 
						ctx.getPackageName()));
			}
		}
		
        // set icon fonts
		Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "HelveFMBrussel.ttf");
		venueName.setTypeface(font);
		Typeface iconFont = Typeface.createFromAsset(getActivity().getAssets(), "icomoon.ttf");
		addReviewIcon.setTypeface(iconFont);
		TextView addressIcon = (TextView) v.findViewById(R.id.detail_map_btn_icon);
		addressIcon.setTypeface(iconFont);
		TextView websiteIcon = (TextView) v.findViewById(R.id.detail_website_btn_icon);
		websiteIcon.setTypeface(iconFont);
		TextView phoneIcon = (TextView) v.findViewById(R.id.detail_phone_btn_icon);
		phoneIcon.setTypeface(iconFont);
		audioIcon.setTypeface(iconFont);
		
		// set viewswitcher
		toggleView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
			// TODO Auto-generated method stub
			//	Intent intent = new Intent(getApplicationContext(), ShowMap.class);
			//	startActivity(intent);
				
				detailSwitcher.showNext();
			}
		});		
		
		venueName.setText(currentVenue.getName()); 
		venueAddress.setText(currentVenue.getAddress());
		venueDescription.setText(currentVenue.getDescription());
		phoneText = (TextView)v.findViewById(R.id.detail_venuePhone);
		if(currentVenue.getPhone() != null && !currentVenue.getPhone().equals("")){
			phoneText.setText(currentVenue.getPhone());
			final RelativeLayout phoneLayout = (RelativeLayout)v.findViewById(R.id.detail_phone_btn);
			phoneLayout.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(Intent.ACTION_CALL);
					intent.setData(Uri.parse(currentVenue.getPhone()));
					startActivity(intent);
				}
			});
		}
			
		urlText = (TextView)v.findViewById(R.id.detail_venueWebsite);
		if(currentVenue.getUrl() != null && !currentVenue.getUrl().equals("")){
			urlText.setText(currentVenue.getUrl());
			final RelativeLayout urlLayout = (RelativeLayout)v.findViewById(R.id.detail_website_btn);
			urlLayout.setOnClickListener(new OnClickListener() {		
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setData(Uri.parse(currentVenue.getUrl()));
					startActivity(intent);
				}
			});
		}
		
		final RelativeLayout addressLayout = (RelativeLayout)v.findViewById(R.id.detail_map_btn);
		addressLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				StringBuilder sb = new StringBuilder();
				LatLng lastLoc = Util.lastLocation;
				sb.append("http://maps.google.com/maps?saddr=");
				sb.append(String.valueOf(lastLoc.latitude));
				sb.append(",");
				sb.append(String.valueOf(lastLoc.longitude));
				sb.append("&daddr=");
				sb.append(String.valueOf(currentVenue.getLatitude()));
				sb.append(",");
				sb.append(String.valueOf(currentVenue.getLongitude()));
				Log.d("MAPSURI", sb.toString());
				Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
						Uri.parse(sb.toString()));
				startActivity(intent);
			}
		});
		
		ratingBar.setRating((float)currentVenue.getRating());
		ratingBar.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				LayoutInflater inflater = getActivity().getLayoutInflater();
				final Dialog ratingDialog = new Dialog(ctx, R.style.LightDialogFmb);
				View myView = inflater.inflate(R.layout.add_rating, null);
				Button cancelButton = (Button)myView.findViewById(R.id.rating_cancel_btn);
				Button submitButton = (Button)myView.findViewById(R.id.rating_submit_btn);
				final RatingBar newRatingBar = (RatingBar)myView.findViewById(R.id.review_add_rating);
				cancelButton.setOnClickListener(new View.OnClickListener(){
					@Override
					public void onClick(View v) {
						Log.d("CANCEL", "rating cancelled");
						ratingDialog.dismiss();					}
				});
				submitButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						float newRating = newRatingBar.getRating();
						if(newRating > 0)
							new ProcessRating().execute(newRating);
						ratingDialog.dismiss();
					}
				});
				ratingDialog.setContentView(myView);
				ratingDialog.show();
				return false;
			}
		});
		
		reviewBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				LayoutInflater inflater = getActivity().getLayoutInflater();
				View reviewView = inflater.inflate(R.layout.add_review, null);
				final Dialog reviewDialog = new Dialog(ctx, R.style.LightDialogFmb);
				Button cancelBtn = (Button)reviewView.findViewById(R.id.review_cancel_btn);
				Button submitBtn = (Button)reviewView.findViewById(R.id.review_submit_btn);
				final EditText nameText = (EditText)reviewView.findViewById(R.id.review_name_input);
				String userName = n_cst_common.of_get_user_name(ctx);
				if(!userName.equals("n/a")){
					nameText.setText(userName);
					nameText.setEnabled(false);
				}
					
				final EditText mailText = (EditText)reviewView.findViewById(R.id.review_mail_input);
				final EditText revText = (EditText)reviewView.findViewById(R.id.review_text_input);
				cancelBtn.setOnClickListener(new OnClickListener() {		
					@Override
					public void onClick(View v) {
						reviewDialog.dismiss();
					}
				});
				submitBtn.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						String user = nameText.getText().toString();
						String mail = mailText.getText().toString();
						String reviewText = revText.getText().toString();
						if(!user.equals("") && !mail.equals("") && !reviewText.equals("")){
							new ProcessReview().execute(user, mail, reviewText);
							reviewDialog.dismiss();
						}
					}
				});
				reviewDialog.setContentView(reviewView);
				reviewDialog.show();
			}
		});
		
		ImageDownloader imgDL = new ImageDownloader(bigImg);
		imgDL.execute(AppConstants.BIG_IMAGE_PATH + currentVenue.getPicUrl());
		// todo: same image or different for footer?
		ImageDownloader imgDL2 = new ImageDownloader(footerImg);
		imgDL2.execute(AppConstants.BIG_IMAGE_PATH + currentVenue.getPicUrl());
		reviews = currentVenue.getReviews();
		Log.d("NRREVIEWS", "nr of reviews: " + reviews.size());
		ListView reviewListView = (ListView)v.findViewById(R.id.detail_reviewList);
		rAdapter = new ReviewAdapter(getActivity().getApplicationContext(), reviews);
		reviewListView.setAdapter(rAdapter);
        return v;
    }
    
    public void setContext(Context ctx){
    	this.ctx = ctx;
    }
    
    public void setDataManager(DataManager dm){
    	this.dm = dm;
    }
    
    private class ProcessRating extends AsyncTask<Float, Integer, Void>{

		@Override
		protected Void doInBackground(Float... params) {
			float newRating = params[0];
			if(newRating > 0)
				Log.d("NEWRATING", "new Rating: " + params[0]);
			return null;
		}
    	
    }
    
    private class ProcessReview extends AsyncTask<String, Integer, Boolean>{

    	@Override
    	protected void onPostExecute(Boolean result) {
    		if(result){
    			rAdapter.clear();
    			rAdapter.addAll(reviews);
    			rAdapter.notifyDataSetChanged();
    		}
    		super.onPostExecute(result);
    	}
    	
		@Override
		protected Boolean doInBackground(String... params) {
			String userName = params[0];
			String email = params[1];
			String text = params[2];
			Review review = new Review(currentVenue.getJsonId(), 
					text, new Date().getTime() / 1000, userName);
			dm.saveReview(review);
			reviews.add(review);
			currentVenue.setReviews(reviews);
			return true;
		}
    	
    }

	@Override
	public boolean canPause() {
		return true;
	}

	@Override
	public boolean canSeekBackward() {
		return true;
	}

	@Override
	public boolean canSeekForward() {
		return true;
	}

	@Override
	public int getBufferPercentage() {
		return 0;
	}

	@Override
	public int getCurrentPosition() {
		return player.getCurrentPosition();
	}

	@Override
	public int getDuration() {
		return player.getDuration();
	}

	@Override
	public boolean isPlaying() {
		return player.isPlaying();
	}

	@Override
	public void pause() {
		player.pause();
	}

	@Override
	public void seekTo(int i) {
		player.seekTo(i);
	}

	@Override
	public void start() {
		player.start();
	}
	
	public boolean onTouchEvent(MotionEvent event) {
	    //the MediaController will hide after 3 seconds - tap the screen to make it appear again
			controller.show();
	    return true;
	}
	
	@Override
	public void onStop() {
		if(player != null){
			player.release();
			player = null;
		}
		if(controller != null){
			controller = null;
		}
		super.onStop();
	}
	
	@Override
	public void onPause(){
		super.onPause();
		if(controller != null)
			controller.hide();
	}
    
}
